<template>
    <el-container class="jxc_fin_container">
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header" class="fin_header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="searchForm"
                                @event="handleHeaderEvent">
                    <template slot="left_search">
                        <div class="tip" v-if="type === 'sale'">余额是客户在本公司的预付款余额</div>
                        <div class="tip" v-else>余额是本公司在提供商的预付款的余额</div>
                    </template>
                    <template slot="right_search">
                        <el-select v-model="searchForm.account_type" placeholder="请选择"
                                   class="w100" clearable @change="getList(true)"
                                   style="margin-right: 5px;">
                            <el-option label="全部类型" value="" />
                            <el-option v-for="(item, index) in typeList" :key="index"
                                       :label="item.display_text" :value="item.value" />
                        </el-select>
                    </template>
                </headerTemplate>
                <div class="card_content">
                    <el-row :gutter="15">
                        <el-col :span="6">
                            <vxeTableTemplate ref="$account" :data="accountList" :options.sync="accountTableOptions"
                                              @event="handleAccountTableEvent" />
                        </el-col>
                        <el-col :span="18">
                            <vxeTableTemplate ref="$table" :data="dataList" :options.sync="tableOptions"
                                              @event="handleTableEvent" />
                        </el-col>
                    </el-row>
                </div>
            </el-card>
        </el-main>
    </el-container>
</template>

<script>
import poiApi from "@common/api/poiApi";
import tableRender from "@common/components/common/tableRender";
import SaleOrderForm from "@jxc/views/sale/components/SaleOrderForm";
import SaleReturnBillForm from "@jxc/views/sale/components/SaleReturnBillForm";
import BuyOrderForm from "@jxc/views/buy/components/BuyOrderForm";
import BuyReturnBillForm from "@jxc/views/buy/components/BuyReturnBillForm";
import FinanceForm from "../dialog/FinanceForm";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "JxcFinance",
    props: {
        type: {
            type: String,
            default: 'sale',
        },
        permission: {
            type: Object,
            default() {
                return {};
            },
        },
    },
    data() {
        const _this = this;
        return {
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            _this.getAccountList();
                        },
                    },
                    {
                        id: "add",
                        icon: "fa fa-plus",
                        type: "primary",
                        show: true,
                        permission: _this.permission.add,
                        method: () => {
                            _this.openDialog(null, 'add');
                        },
                    },
                    {
                        id: "export",
                        type: "success",
                        show: true,
                        icon: "el-icon-download",
                        label: '导出',
                        class: 'export_btn',
                        permission: _this.permission.export,
                        method: () => {
                            _this.handleExport();
                        },
                    },
                ],
                toolbar_filter: [
                    { type: "text", field: "code", label: "单据号码", permission: [ 'sale', 'buy' ] },
                    {
                        type: "daterange",
                        field: "the_date",
                        label: "单据日期",
                        style: { width: '200px' },
                        permission: [ 'sale', 'buy' ],
                    },
                ],
            },
            clientOptions: {
                disabled: false,
                placeholder: '请选择客户',
                bottomAction: {
                    permission: 'save_sys_client',
                    permissionUrl: '/sysClients',
                },
            },
            typeList: [],
            searchForm: {
                account_type: '',
            },
            accountList: [],
            accountTableOptions: {
                ref: "JxcFinAccountTable",
                container: ".jxc_fin_container",
                radioSelect: true,
                rowConfig: {
                    isCurrent: true,
                },
                radioHeader(h, params) {
                    return tableRender.renderElLink(h, params, {
                        type: 'primary',
                        text: '全部',
                        underline: false,
                        style: {
                            fontSize: '12px',
                            fontWeight: '700',
                            verticalAlign: 'top',
                        },
                        click() {
                            _this.currSelectData = undefined;
                            delete _this.searchForm.client_sid;
                            delete _this.searchForm.supplier_sid;
                            if (_this.$refs.$account) {
                                _this.$refs.$account.clearSelection();
                            }
                            _this.getList(true);
                        },
                    });
                },
                columns: [],
                baseColumns: [
                    {
                        label: "客户",
                        prop: "client_display",
                        align: "center",
                        permission: [ 'sale' ],
                    },
                    {
                        label: "供应商",
                        prop: "supplier_display",
                        align: "center",
                        permission: [ 'buy' ],
                    },
                    {
                        label: "账户余额",
                        prop: "amount",
                        align: "right",
                        permission: [ 'sale', 'buy' ],
                        formatter: (row, column, scope) => {
                            let str = _this.formatterAmount(row, column, scope, 2);
                            if (Number(str) < 0) {
                                str = `<span style="color: red;">${ str }</span>`;
                            }
                            return str;
                        },
                    },
                ],
                pagination: false,
            },
            dataList: [],
            selectionList: [],
            tableOptions: {
                ref: `${ _this.type }JxcFinTable`,
                container: ".jxc_fin_container",
                columns: [],
                baseColumns: [
                    {
                        label: "客户",
                        prop: "client_display",
                        align: "center",
                        permission: [ 'sale' ],
                    },
                    {
                        label: "供应商",
                        prop: "supplier_display",
                        align: "center",
                        permission: [ 'buy' ],
                    },
                    {
                        label: "单据类型",
                        prop: "account_type_name",
                        align: "center",
                        width: 90,
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "单据日期",
                        prop: "the_date",
                        align: "center",
                        width: 90,
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "账单号码",
                        prop: "code",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "账单金额",
                        prop: "amount",
                        align: 'right',
                        permission: [ 'sale', 'buy' ],
                        formatter: (row, column, scope) => {
                            let str = _this.formatterAmount(row, column, scope, 2);
                            let filter = _this.typeList.filter(item => item.key3 === row.account_type);
                            if (_this.$utils.isNotEmptyList(filter)) {
                                if (filter[0].value === '+') {
                                    str = `<span style="color: green;">${ filter[0].value }${ str }</span>`;
                                } else {
                                    str = `<span style="color: red;">${ filter[0].value }${ str }</span>`;
                                }
                            }
                            return str;
                        },
                    },
                    {
                        label: "摘要",
                        prop: "note_info",
                        align: 'center',
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "关联单据号码",
                        prop: "relation_code",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "账户余额",
                        prop: "remain_amount",
                        align: "right",
                        permission: [ 'sale', 'buy' ],
                        formatter: (row, column, scope) => {
                            let str = _this.formatterAmount(row, column, scope, 2);
                            if (Number(str) < 0) {
                                str = `<span style="color: red;">${ str }</span>`;
                            }
                            return str;
                        },
                    },
                    {
                        label: "资金账号",
                        prop: "fund_account_name",
                        align: "right",
                        permission: [ 'sale', 'buy' ],
                    },
                ],
                operates: {
                    fixed: "right",
                    list: [
                        {
                            id: "detail",
                            icon: "fa fa-info-circle",
                            type: "warning",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "详情",
                            },
                            method: (index, row) => {
                                _this.openDialog(row, 'detail');
                            },
                        },
                        {
                            id: "detail",
                            icon: "el-icon-notebook-1",
                            type: "primary",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "关联单据",
                            },
                            permission: _this.permission.relation,
                            filter(row) {
                                return _this.$utils.isNotEmpty(row.relation_sid);
                            },
                            method: (index, row) => {
                                _this.openBillDialog(row);
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
            currSelectData: undefined,
        };
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            this.initOptions();
            this.initAccountTypeList();
            this.getAccountList();
        },
        getAccountList() {
            const _this = this;
            _this.fetchData(_this.$api.API_FindJxcFinanceAccounts, {
                type: _this.type,
                nopage: '1',
            }).then(result => {
                _this.accountList = result.data || [];
                _this.accountTableOptions = _this.setTableTotal(_this.accountTableOptions, result);
                _this.getList(true);
            }).catch(() => {
            });
        },
        handleAccountTableEvent(event) {
            const _this = this;
            if (event.type === 'radioChange') {
                console.log(event.value);
                _this.currSelectData = event.value;
                _this.searchForm = $.extend({}, _this.searchForm, {
                    client_sid: event.value.client_sid,
                    supplier_sid: event.value.supplier_sid,
                });
                _this.getList(true);
            }
        },
        initOptions() {
            const _this = this;
            let accountColumns = _this.accountTableOptions.baseColumns.map(item => $.extend({}, item));
            accountColumns = accountColumns.filter(item => item.permission.indexOf(_this.type) !== -1);
            _this.accountTableOptions = $.extend({}, _this.accountTableOptions, { columns: accountColumns });
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            columns = columns.filter(item => item.permission.indexOf(_this.type) !== -1);
            _this.tableOptions = $.extend({}, _this.tableOptions, { columns });
        },
        initAccountTypeList() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindCommonParameterValuesByKey, {
                key1: 'jxc_account_type',
                key2: _this.type,
            }).then(res => {
                _this.typeList = res.data || [];
            }).catch(() => {
            });
        },
        handleHeaderEvent(event) {
            const _this = this;
            _this.searchForm = $.extend({}, _this.searchForm, event.searchForm);
            if (event.type === "search") {
                _this.getList(true);
            } else if (event.type === "refresh") {
                _this.getList(true);
            }
        },
        getList(query) {
            const _this = this;
            if (query) {
                _this.tableOptions = _this.resetTablePagination(_this.tableOptions);
            }
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            queryData.type = _this.type;
            _this.fetchData(_this.$api.API_FindJxcFinanceAccountDetails, queryData).then(result => {
                _this.dataList = result.data || [];
                _this.tableOptions = _this.setTableTotal(_this.tableOptions, result);
            }).catch(() => {
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        openDialog(row, type) {
            const _this = this;
            if (type === 'edit' && row == null) {
                if (!_this.checkSelection(_this.selectionList, false)) {
                    return;
                }
                row = _this.selectionList[0];
            }
            if (!row) {
                row = {};
            }
            let detail = type === 'detail';
            _this.$dialog({
                title: _this.type === 'sale' ? '销售对账' : '采购对账',
                width: '1000px',
                component: {
                    value: FinanceForm,
                    props: {
                        detail,
                        row,
                        type: _this.type,
                        typeList: _this.typeList,
                    },
                },
                hideConfirmBtn: detail,
                confirmed() {
                    _this.getAccountList();
                },
            });
        },
        openBillDialog(row) {
            const _this = this;
            let component = undefined;
            let title = '';
            if (_this.type === 'sale') {
                component = row.account_type.indexOf('_return') !== -1 ? SaleReturnBillForm : SaleOrderForm;
                title = row.account_type.indexOf('_return') !== -1 ? '销售退货单' : '销售订单';
            } else {
                component = row.account_type.indexOf('_return') !== -1 ? BuyReturnBillForm : BuyOrderForm;
                title = row.account_type.indexOf('_return') !== -1 ? '采购退货单' : '采购订单';
            }
            _this.$dialog({
                title,
                width: '1000px',
                component: {
                    value: component,
                    props: {
                        detail: true,
                        row: {
                            sid: row.relation_sid,
                        },
                    },
                },
                hideConfirmBtn: true,
            });
        },
        deleteConfirm(row) {
            const _this = this;
            _this.storeDispatch('jxc/handleDeleteData', {
                url: _this.$api.API_DeleteJxcSaleOrders,
                row,
                list: _this.selectionList,
                _vm: _this,
                msg_name: _this.type === 'sale' ? '销售对账' : '采购对账',
                state_field: '',
            }).then(res => {
                if (res) {
                    _this.getList();
                }
            });
        },
        handleExport() {
            const _this = this;
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            queryData.type = _this.type;
            queryData.dr = 0;
            let templateName = _this.type === 'sale' ? _this.$api.EXPORT_TEMPLATE_NAME_FIN_SALE : _this.$api.EXPORT_TEMPLATE_NAME_FIN_BUY;
            let outputName = _this.type === 'sale' ? '销售对账' : '采购对账';
            if (_this.currSelectData) {
                outputName = `${ _this.currSelectData.client_display || _this.currSelectData.supplier_display }_${outputName}`;
            }
            poiApi.exportExcelTemplate(templateName, _this.$api.API_FindJxcFinanceAccountDetails, queryData, outputName, {}, undefined, 1, 100, false, true);
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.jxc_fin_container {
    width: 100%;
    height: 100%;

    .fin_header {
        /deep/ .tip {
            padding-left: 10px;
            font-size: 14px;
            font-weight: bold;
            line-height: 34px;
        }
    }
}
</style>
